package com.abu.crms.config.mvc;

import cn.hutool.core.util.StrUtil;
import com.abu.crms.config.exception.CRException;
import com.abu.crms.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            response.sendRedirect("http://localhost:7878/#/login");
            return false;
        }
        jwtUtils.verifyToken(token);

        Map<String, String> managerInfoMap = jwtUtils.getInfoFromToken(token);
        String managerId = managerInfoMap.get("managerId");
        THREAD_LOCAL.set(managerId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
    }

    public static String getManagerId() {
        return THREAD_LOCAL.get();
    }
}
